package top.superxuqc.autocheckincqupt.checkinconsumer.service;

import com.alibaba.fastjson.JSONObject;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import top.superxuqc.autocheckincqupt.api.CheckInService;
import top.superxuqc.autocheckincqupt.checkinconsumer.dao.DealRedisDao;
import top.superxuqc.autocheckincqupt.checkinconsumer.domain.CQUPTStu;


import top.superxuqc.autocheckincqupt.domain.ApiResult;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.concurrent.Executor;
import java.util.concurrent.Executors;

/**
 * 请填写类的描述
 *
 * @author xuqicheng1
 * @date 2021-08-03 12:25
 */
@Service
@Lazy(value = false)
public class DealCheckService {
    @Autowired
    CheckInService service;

    @Autowired
    DealRedisDao dao;

    private Executor executor = Executors.newFixedThreadPool(5);

    @Scheduled(cron = "0 0 0,7,10 * * ?")
    public void check(){
        ApiResult<List<String>> resultT = new ApiResult<List<String>>();
        resultT.setData(new ArrayList<>());
        service.sendGroupKey("开始打卡任务...如果没@你，就是你已经打过卡了\n","这是一条全体消息~",resultT);
        Set<CQUPTStu> infos = dao.getInfos();
        for (CQUPTStu stu:infos
             ) {
            executor.execute(new Runnable() {
                @Override
                public void run() {
                    DealCheckService.this.run(stu);
                }
            });
        }
    }
    public ApiResult<List<String>> tryCheck(CQUPTStu stu){
        return service.startCheckIn(stu.getOpenId(), stu.getXh(), stu.getAddress(), stu.getQq());
    }
    public void save(CQUPTStu stu){
        dao.saveSTU(stu);
    }

    private void run(CQUPTStu stu){
        ApiResult<List<String>> result = service.startCheckIn(stu.getOpenId(), stu.getXh(), stu.getAddress(), stu.getQq());
        if(!result.getCode().equals("200") && !result.getCode().equals("201")){
            service.sendGroupKey(JSONObject.toJSONString(result),stu.getQq(),result);
        }
        System.out.println(JSONObject.toJSONString(result));
    }
}
